(in-package :com.yanbo.mp3-server)
;;;该文件包含MP3数据库基本操作
;数据库全局变量
(defvar *db* nil)

;创建cd数据记录，plist,rating为等级、评价、收听率
(defun make-cd (title artist rating ripped)
  (list :title title :artist artist :rating rating :ripped ripped))

;将cd数据记录加入*db*变量
(defun add-record (cd)
  (push cd *db*))

;查看数据库内容,~{和~}指令通知format在list上进行循环操作
(defun dump-db ()
  (dolist (cd *db*)
    (format t "~{~a: ~10t~a~%~}~%" cd)))

;查看数据库内容,完全使用format控制符指令
(defun dump-db-1 ()
  (format t "~{~{~a: ~10t~a~%~}~%~}" *db*))

;人机交互函数
(defun prompt-read (prompt)
  (format *query-io* prompt)
  (force-output *query-io*)
  (read-line *query-io*))

;交互输入cd信息
(defun prompt-for-cd ()
  (make-cd
   (prompt-read "Title:")
   (prompt-read "Artist:")
   ;parse-integer 解析失败返回NIL，本代码使其返回0
   (or (parse-integer (prompt-read "Rating:") :junk-allowed t) 0)
   (y-or-n-p "Ripped [y/n]:")))

;批量输入cd信息，直至停止
(defun add-cds ()
  (loop (add-record (prompt-for-cd))
     (if (not (y-or-n-p "Another? [y/n]:")) (return))))

;保存mp3数据文件
(defun save-db (filename)
  (with-open-file (out filename
                       :direction :output
                       :if-exists :supersede)
    (with-standard-io-syntax
      (print *db* out))))

;加载数据到*db*变量
(defun load-db (filename)
  (with-open-file (in filename)
    (with-standard-io-syntax
      (setf *db* (read in)))))

;查询数据库，按艺术家
(defun select-by-artist (artist)
  (remove-if-not
   #'(lambda (cd) (equal (getf cd :artist) artist))
   *db*))

;select函数
(defun select (select-fn)
  (remove-if-not select-fn *db*))

;通用的where查询
(defun where (&key title artist rating (ripped nil ripped-p))
  #'(lambda (cd)
      (and
       (if title (equal (getf cd :title) title) t)
       (if artist (equal (getf cd :artist) artist) t)
       (if rating (equal (getf cd :rating) rating) t)
       (if ripped-p (equal (getf cd :ripped) ripped) t))))

;update函数
(defun update (select-fn &key title artist rating (ripped nil ripped-p))
  (setf *db*
        (mapcar
         #'(lambda (row)
             (when (funcall select-fn row)
               (if title (setf (getf row :title) title))
               (if artist (setf (getf row :artist) artist))
               (if rating (setf (getf row :rating) rating))
               (if ripped-p (setf (getf row :ripped) ripped)))
             row)
         *db*)))

;delete函数
(defun delete-rows (select-fn)
  (setf *db* (remove-if select-fn *db*)))

;
(defun make-comparisons-expr (field value)
  `(equal (getf cd ,field) ,value))

;
(defun make-comparisons-list (fields)
  (loop while fields
       collecting (make-comparisons-expr (pop fields) (pop fields))))

;where宏
(defmacro where (&rest clauses)
  `#'(lambda (cd) (and ,@(make-comparisons-list clauses))))

;;;;; 
